﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.IO;
using System.Configuration;
using CompanyBussiness;

namespace Website.admin.Control
{
    public partial class cCreateNews : System.Web.UI.UserControl
    {
        NewsManagement newsMana = new NewsManagement();
        LanguagesManagement languageMana = new LanguagesManagement();
        CompanyBussiness.Category category;
        CompanyBussiness.Language language;
        CompanyBussiness.New news;
        CheckValid cv = new CheckValid();
        string strFileName = "";
        bool AddOrUp = false;
        int STRnewsID;
        string error = "";
        string modulCode;
        string cateNameContact = "";
        bool ImgStatus = true;

        protected void Page_Load(object sender, EventArgs e)
        {
            modulCode = Request.QueryString["Mod"];
            loadModul();

            if (Request.Cookies[CONST.COOKIES_LANGUAGE] == null)
            {
                Session[CONST.SESSION_LANGUAGE] = "";
                language = languageMana.GetLanguageByCode("vi-VN");
            }
            else
            {
                Session[CONST.SESSION_LANGUAGE] = Request.Cookies[CONST.COOKIES_LANGUAGE][CONST.COOKIES_LANGUAGE_ID];
                language = languageMana.GetLanguageByID(int.Parse(Session[CONST.SESSION_LANGUAGE].ToString()));
            }
            this.LoadDropParentCategory();

            if (Request["CategoryNameContact"] != null)
            {
                AddOrUp = true;
                lbTypeAction.Text = "Nội dung liên hệ";
                Session["CategoryNameContact"] = Request["CategoryNameContact"].ToString();
                this.LoadForm();
                dropParentCategory.Enabled = false;
                dropChildCategory.Enabled = false;
                imgNews.Visible = true;
                btnDelete.Visible = false;
            }
            else
            {
                if (Request[CONST.QUERYSTRING_NEWS] == null || Request.Cookies[CONST.ACTION][CONST.COOKIES_ACTION_TYPE] == "AddNews")
                {
                    AddOrUp = false;
                    btnDelete.Visible = false;
                    txtNewsAccess.ReadOnly = true;
                    lbTypeAction.Text = "Nội dung bài viết";
                    dropChildCategory.Enabled = false;
                }
                else
                {
                    AddOrUp = true;
                    STRnewsID = int.Parse(Request[CONST.QUERYSTRING_NEWS]);
                    this.LoadForm();
                    dropChildCategory.Enabled = true;
                    imgNews.Visible = true;
                    lbTypeAction.Text = "Cập nhật bài viết";
                }
            }

            

            fail.Visible = false;
            success.Visible = false;

        }

        protected void loadModul()
        {
            switch (modulCode)
            {
                case "MNEWS":
                    {
                        //Tin tức 
                    }
                    break;
                case "MSHAREHOLDERS":
                    {
                        //Cổ đông
                    }
                    break;
                case "MJOB":
                    {
                        //Tin tuyển dụng 
                    }
                    break;
                case "MHELP":
                    {
                        //Trợ giúp
                        rowSrource.Visible = false;
                        rowLinkSource.Visible = false;
                    }
                    break;
                case "MCONTACT":
                    {
                        //Liên hệ
                        lbNewsIntro.Text = "Số điện thoại và fax liên hệ:";
                        lbConditions.Visible = false;
                        TextBoxCounterIntro.Visible = false;
                        dropParentCategory.Enabled = false;
                        dropChildCategory.Enabled = false;

                        lbNewsContent.Text = "Nội dung liên hệ:";
                        lbNewsSource.Text = "Địa chỉ:";
                        lbNewsLink.Text = "Địa chỉ Website:";

                        rowFileupload.Height = "0px";
                    }
                    break;
                case "MINTRO":
                    {
                        //Giới thiệu
                        rowSrource.Visible = false;
                        rowLinkSource.Visible = false;
                        rowFileupload.Height = "0px";
                    }
                    break;
            }


        }

        protected void LoadDropParentCategory()
        {
            try
            {
                dropParentCategory.Items.Clear();
                //dropParentCategory.Items.Add("--- Danh mục cha ---");
                //List<Category> listParentCategory = newsMana.GetParentCategory(language.LanguagesID,true,modulCode);
                //foreach (var li in listParentCategory)
                //{
                //    dropParentCategory.Items.Add(li.CategoryName);
                //}
                dropParentCategory.DataSource = newsMana.GetParentCategory(language.LanguagesID, true, modulCode);
                dropParentCategory.DataTextField = "CategoryName";
                dropParentCategory.DataValueField = "CategoryID";
                dropParentCategory.DataBind();
                dropParentCategory.Items.Insert(0,new ListItem("--- Danh mục cha ---","0"));
            }
            catch (Exception)
            {
                fail.Visible = true;
                lbError.Text = "Có lỗi trong khi load dữ liệu . Bạn hãy thử lại.";
            }
        }

        protected void LoadDropChildCategory(int parentCategoryID)
        {
            try
            {
                dropChildCategory.Enabled = true;
                dropChildCategory.Items.Clear();

                List<Category> listChildCategory = newsMana.GetChildrenCategoryByParentID(parentCategoryID, language.LanguagesID, true,modulCode);
                if (listChildCategory.Count == 0)
                {
                    dropChildCategory.Enabled = false;
                }
                //foreach (var li in listChildCategory)
                //{
                //    dropChildCategory.Items.Add(li.CategoryName);
                //}
                dropChildCategory.DataSource = newsMana.GetChildrenCategoryByParentID(parentCategoryID, language.LanguagesID, true, modulCode);
                dropChildCategory.DataTextField = "CategoryName";
                dropChildCategory.DataValueField = "CategoryID";
                dropChildCategory.DataBind();

            }
            catch (Exception)
            {
                fail.Visible = true;
                lbError.Text = "Có lỗi trong khi load dữ liệu . Bạn hãy thử lại.";
            }
        }

        protected void FormatForm()
        {
            try
            {
                if (AddOrUp == false)
                {
                    txtNewsSubject.Text = "";
                    txtNewsAuthor.Text = "";
                    txtNewsIntro.Text = "";
                    txtNewsSource.Text = "";
                    txtNewsLink.Text = "";
                    txtNewsDateCreate.Text = "";
                    txtNewsDate.Text = "";
                    txtNewsAccess.Text = "";
                    imgNews.ImageUrl = ConfigurationManager.AppSettings["NoImages"];
                    txtNewsContent.Value = "";
                    Session[CONST.SESSION_IMG] = null;
                    Session[CONST.SESSION_IMG_THUMBNAIL] = null;
                }
                else
                {
                    this.LoadForm();
                    Session[CONST.SESSION_IMG] = null;
                    Session[CONST.SESSION_IMG_THUMBNAIL] = null;
                }
            }
            catch (Exception)
            { }
        }

        protected bool GetData()
        {
            if (txtNewsSubject.Text.Trim() != "")
            {
                news.NewsSubject = txtNewsSubject.Text;
            }
            else
            {
                fail.Visible = true;
                lbError.Text = "Bạn chưa nhập tiêu đề cho bài viết !";
                return false;
            }

            if (txtNewsIntro.Text.Trim() != "")
            {
                if (TextBoxCounterIntro.Characters > Int32.Parse(ConfigurationManager.AppSettings["MaxIntroduction"].ToString()))
                {
                    fail.Visible = true;
                    lbError.Text = "Lời giới thiệu không cho phép vượt quá " + ConfigurationManager.AppSettings["MaxIntroduction"] + " ký tự.";
                    return false;
                }
                else
                {
                    news.NewsIntro = txtNewsIntro.Text;
                }
            }
            else
            {
                news.NewsIntro = "";
            }

            if (txtNewsAuthor.Text != "")
            {
                news.NewsAuthor = txtNewsAuthor.Text;
            }
            else
            {
                news.NewsAuthor = "" + Session[CONST.SESSION_ACCOUNTUSER].ToString();
            }

            if (txtNewsContent.Value.ToString() != "")
            {

                news.NewsContent = txtNewsContent.Value.ToString();
            }
            else
            {
                news.NewsContent = "";
            }

            if (checkStatus.Checked == true)
            {
                news.NewsStatus = true;
            }
            else
            {
                news.NewsStatus = false;
            }

            if (Session["CategoryNameContact"] == null)
            {
                if (dropParentCategory.SelectedValue == "0")
                {
                    fail.Visible = true;
                    lbError.Text = "Bạn chưa chọn danh mục !";
                    return false;
                }
                else
                {
                    if (dropChildCategory.Items.Count == 0)
                    {
                        //category = newsMana.GetCategoryByNameSingle(dropParentCategory.SelectedValue.ToString(), modulCode);
                        category=newsMana.GetCategoryByID(int.Parse(dropParentCategory.SelectedValue.ToString()),modulCode);
                    }
                    else
                    {
                        //category = newsMana.GetCategoryByNameSingle(dropChildCategory.SelectedValue.ToString(), modulCode);
                        category = newsMana.GetCategoryByID(int.Parse(dropChildCategory.SelectedValue.ToString()), modulCode);
                    }
                }
            }
            else
            {
                category = newsMana.GetCategoryByNameSingle("MCONTACT", "MCONTACT");
            }

            if (Session[CONST.SESSION_IMG_THUMBNAIL] == null)
            {
                news.NewsImage = "";
            }
            else
            {
                news.NewsImage = ConfigurationManager.AppSettings["FolderImagesUpload"] + Session[CONST.SESSION_IMG_THUMBNAIL];
            }


            if (txtNewsSource.Text.Trim() != "")
            {
                news.NewsSource = txtNewsSource.Text;
            }
            else
            {
                news.NewsSource = "";
            }

            if (txtNewsLink.Text.Trim() != "")
            {
                news.NewsLink = txtNewsLink.Text;
            }
            else
            {
                news.NewsLink = "";
            }

            if (Session[CONST.SESSION_FILE_ATTACH] == null)
            {
                news.FileAttach = null;
            }
            else
                news.FileAttach = ConfigurationManager.AppSettings["FolderFileUpload"] + Session[CONST.SESSION_FILE_ATTACH];

            if (checkImgStatus.Checked)
            {
                ImgStatus = true;
            }
            else
            {
                ImgStatus = false;
            }

            return true;
        }

        protected void btnSave_Click(object sender, EventArgs e)
        {
            try
            {
                if (AddOrUp == false)
                {
                    #region Addnew

                    news = new New();

                    if (GetData() == false)
                        return;
                    
                    news.NewsDateCreate = DateTime.Now;

                    if (txtNewsAccess.Text.Trim() != string.Empty)
                    {
                        if (cv.CheckNumber(txtNewsAccess.Text.Trim()))
                        {
                            news.NewsAccess = int.Parse(txtNewsAccess.Text.Trim());
                        }
                        else
                        {
                            fail.Visible = true;
                            lbError.Text = "Nếu bạn sửa số lượng đọc tin thì bắt buộc phải nhập số";
                            return;
                        }
                    }
                    else
                    {
                        news.NewsAccess = 0;
                    }
                    
                    //tao moi tin bai
                    int idOut= newsMana.CreateNews(news.NewsSubject, news.NewsIntro, news.NewsContent, news.NewsAuthor, news.NewsSource, news.NewsLink, (DateTime)news.NewsDateCreate, (int)news.NewsAccess, news.NewsImage, (Boolean)news.NewsStatus,news.FileAttach,ImgStatus, (int)category.CategoryID);

                    //Tao metadata cho tin bai
                    Metadata meta = new Metadata();
                    meta.NewsID = idOut;
                    newsMana.CreateMetadata(meta);

                    //Cap nhat meta cho danh muc vua tao
                    Response.Cookies[CONST.ACTION][CONST.COOKIES_ACTION_NAME] = "CreateMetadata";
                    Response.Redirect("Administrator.aspx?" + CONST.ACTION + "=CreateMetadata&Mod=" + modulCode + "&" + CONST.QUERYSTRING_NEWS + "=" + idOut);


                    success.Visible = true;
                    lbSuccess.Text = "Bạn đã thêm mới bài viết !";

                    dropParentCategory.SelectedIndex=0;
                    dropChildCategory.Items.Clear();
                    dropChildCategory.Enabled = false;

                    this.FormatForm();

                    #endregion
                }
                else
                {
                    #region Update

                    if (Session["CategoryNameContact"] != null)
                    {
                        category = newsMana.GetCategoryByNameSingle("MCONTACT", "MCONTACT");
                        news = newsMana.GetNewsOneByCategoryName("MCONTACT",language.LanguagesID);
                    }
                    else
                    {
                        news = newsMana.GetNewsByID(STRnewsID);
                    }
                    

                    if (GetData() == false)
                        return;

                    news.NewsDate = DateTime.Now;

                    if (txtNewsAccess.Text.Trim() != string.Empty)
                    {
                        if (cv.CheckNumber(txtNewsAccess.Text.Trim()))
                        {
                            news.NewsAccess = int.Parse(txtNewsAccess.Text.Trim());
                        }
                        else
                        {
                            fail.Visible = true;
                            lbError.Text = "Nếu bạn sửa số lượng đọc tin thì bắt buộc phải nhập số";
                            return;
                        }
                    }
                    else
                    {
                        news.NewsAccess = 0;
                    }

                    newsMana.UpdateNews((int)news.NewsID, news.NewsSubject, news.NewsIntro, news.NewsContent, news.NewsAuthor, news.NewsSource, news.NewsLink, (DateTime)news.NewsDate, (int)news.NewsAccess, news.NewsImage, (Boolean)news.NewsStatus,news.FileAttach,ImgStatus, (int)category.CategoryID);

                    success.Visible = true;
                    lbSuccess.Text = "Bạn đã cập nhật bài viết !";

                    this.LoadForm();

                    #endregion
                }
            }
            catch (Exception ex)
            {
                //fail.Visible = true;
                //lbError.Text = "Có lỗi trong khi sử lý dữ liệu . Bạn hãy kiểm tra lại.";
            }   
        }

        protected void btnCancel_Click(object sender, EventArgs e)
        {
            this.FormatForm();
        }

        protected void btnDelete_Click(object sender, EventArgs e)
        {
            try
            {
                news = newsMana.GetNewsByID(STRnewsID);
                newsMana.DeleteNews(news.NewsID);

                Response.Cookies[CONST.ACTION][CONST.COOKIES_ACTION_NAME] = "CreateCategory";
                Response.Redirect("Administrator.aspx?" + CONST.ACTION + "=CreateCategory");
            }
            catch (Exception)
            {
                fail.Visible = true;
                lbError.Text = "Có lỗi trong khi sử lý dữ liệu . Bạn hãy kiểm tra lại.";
            }
        }

        protected void LoadForm()
        {
            try
            {
                if (Session["CategoryNameContact"] != null)
                {
                    category = newsMana.GetCategoryByNameSingle("MCONTACT", "MCONTACT");
                    news = newsMana.GetNewsOneByCategoryName("MCONTACT",language.LanguagesID);
                }
                else
                {
                    news = newsMana.GetNewsByID(STRnewsID);
                }
                
                txtNewsSubject.Text = news.NewsSubject.ToString();

                if (news.NewsIntro != null)
                    txtNewsIntro.Text = news.NewsIntro.ToString();
                else
                    txtNewsIntro.Text = "";

                if (news.NewsAuthor != null)
                    txtNewsAuthor.Text = news.NewsAuthor.ToString();
                else
                    txtNewsAuthor.Text = "";

                if (news.NewsContent != null)
                    txtNewsContent.Value = news.NewsContent.ToString();
                else
                    txtNewsContent.Value = "";

                int CateID = (int)news.CategoryID;

                Category _category = newsMana.GetCategoryByID(CateID,modulCode);

                if (_category.ParentCategoryID != null)
                {
                    dropParentCategory.SelectedValue = newsMana.GetCategoryByID((int)_category.ParentCategoryID,modulCode).CategoryName.ToString();
                    this.LoadDropChildCategory((int)_category.ParentCategoryID);
                    dropChildCategory.SelectedValue = newsMana.GetCategoryByID(CateID,modulCode).CategoryName.ToString();
                }
                else
                {
                    dropParentCategory.SelectedValue = _category.CategoryName;
                }

                if (news.NewsStatus == true)
                    checkStatus.Checked = true;
                else
                    checkStatus.Checked = false;

                if (news.NewsSource != null)
                    txtNewsSource.Text = news.NewsSource.ToString();
                else
                    txtNewsSource.Text = "";

                if (news.NewsLink != null)
                    txtNewsLink.Text = news.NewsLink.ToString();
                else
                    txtNewsLink.Text = "";

                if (news.NewsDateCreate != null)
                    txtNewsDateCreate.Text = news.NewsDateCreate.ToString();
                else
                    txtNewsDateCreate.Text = "";

                if (news.NewsDate != null)
                    txtNewsDate.Text = news.NewsDate.ToString();
                else
                    txtNewsDate.Text = "";

                if (news.NewsAccess != null)
                    txtNewsAccess.Text = news.NewsAccess.ToString();
                else
                    txtNewsAccess.Text = "";

                if (news.NewsImage != null)
                    imgNews.ImageUrl = news.NewsImage.ToString();
                else
                    imgNews.ImageUrl = ConfigurationManager.AppSettings["NoImages"];

                if (news.FileAttach != null)
                {
                    linkFileAttach.NavigateUrl = Server.MapPath(news.FileAttach);
                    linkFileAttach.Text = Path.GetFileName(Server.MapPath(news.FileAttach));
                }

                if (news.ImagesStatus == true)
                {
                    checkImgStatus.Checked = true;
                }
                else
                    checkImgStatus.Checked = false;
                    
            }
            catch (Exception)
            {
                fail.Visible = true;
                lbError.Text = "Có lỗi trong khi Load dữ liệu . Bạn hãy kiểm tra lại.";
            }

        }

        protected void dropParentCategory_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (dropParentCategory.SelectedValue.ToString() != "0")
            {
                //category = newsMana.GetCategoryByNameSingle(dropParentCategory.SelectedValue.ToString(),modulCode);
                category=newsMana.GetCategoryByID(int.Parse(dropParentCategory.SelectedValue.ToString()),modulCode);
                this.LoadDropChildCategory(category.CategoryID);
            }           
        }

    }
}